<?php

abstract class Model extends Base
{
	protected $db;
	protected $table;
	protected $lastId;
	protected $msg = '';

	public function __construct()
	{
		$config = config('db');
		$this->db = DB::getInstance(
            $config['host'],
            $config['user'],
            $config['pass'],
            $config['name'],
            $config['driver'],
            $config['prefix']
            );
        if(!$this->db){
        	new DebugError('连接数据库失败');
        }
		$this->db->exec('set names utf8');
	}

	public function add($data, $table=null)
	{
		if(empty($data)){
			$this->msg = "传入的数据为空";
			return false;
		}
		if(empty($table)){
			$table = $this->table;
		}
		if(empty($data['created'])){
			$data['created'] = time();
		}
		if(empty($data['updated'])){
			$data['updated'] = time();
		}
		$result = $this->db->save($table, $data);
		if($result) $this->msg = "数据保存成功";
		$this->lastId = $this->db->lastInsertId();
		return $result;
	}
	
	public function isExists($where, $table=null)
	{
		if(empty($table))
			$table = $this->table;
		return ($this->db->count($table, $where) > 0); 
	}
	
	public function addNotExists($data, $where, $table=null)
	{
		if(empty($table)) $table = $this->table;
		if($this->isExists($where, $table)){
			$this->msg = '数据已经存在';
			return false;
		}
		return $this->add($data, $table);
	}

	public function __set($var, $val)
	{
		new DebugError('不能改变受保护或私有的成员变量的值');
	}

	public function __get($var)
	{
		if($var == 'lastId' || $var == 'msg'){
			return $this->$var;
		}else{
			new DebugError("你访问的变量 $var 不存在或者它不是 public 变量");
		}
	}
}